import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface CartItem {
  id: string
  title: string
  image: string
  price: number
  quantity: number
  checked: boolean
}

export const useCartStore = defineStore('cart', () => {
  // 购物车条目
  const items = ref<CartItem[]>([
    {
      id: '1001',
      title: '示例商品A 500g 新鲜直达',
      image: '/vite.svg',
      price: 29.9,
      quantity: 1,
      checked: true
    },
    {
      id: '1002',
      title: '示例商品B 1kg 家庭装',
      image: '/vite.svg',
      price: 49.5,
      quantity: 2,
      checked: true
    }
  ])

  // 全选状态
  const allChecked = computed(() => items.value.length > 0 && items.value.every(i => i.checked))
  // 选中数量&金额
  const selectedCount = computed(() => items.value.filter(i => i.checked).reduce((a, b) => a + b.quantity, 0))
  const selectedAmount = computed(() => items.value.filter(i => i.checked).reduce((a, b) => a + b.quantity * b.price, 0))

  const toggleAll = (checked: boolean) => {
    items.value.forEach(i => (i.checked = checked))
  }
  const toggleOne = (id: string, checked: boolean) => {
    const it = items.value.find(i => i.id === id)
    if (it) it.checked = checked
  }
  const setQuantity = (id: string, qty: number) => {
    const it = items.value.find(i => i.id === id)
    if (it) it.quantity = Math.max(1, Math.floor(qty || 1))
  }
  const remove = (id: string) => {
    items.value = items.value.filter(i => i.id !== id)
  }
  const clearChecked = () => {
    items.value = items.value.filter(i => !i.checked)
  }

  const addItem = (payload: Omit<CartItem, 'checked'> & { checked?: boolean }) => {
    const exist = items.value.find(i => i.id === payload.id)
    if (exist) {
      exist.quantity += payload.quantity
    } else {
      items.value.unshift({ ...payload, checked: payload.checked ?? true })
    }
  }

  return {
    items,
    allChecked,
    selectedCount,
    selectedAmount,
    toggleAll,
    toggleOne,
    setQuantity,
    remove,
    clearChecked,
    addItem
  }
})


